package class01.test;


import java.util.Arrays;

/**
 * 选择排序
 */

public class Code01_SelectionSort {
   public static void selectionSort(int[] arr){
        if(arr == null && arr.length < 2){
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            int mixIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                mixIndex = arr[j] < arr[mixIndex] ? j : mixIndex;
            }
            if(i != mixIndex) {
                swap(arr, i, mixIndex);
            }
        }
    }

    private static void swap(int[] arr, int i, int mixIndex) {
        int temp;
        temp = arr[i];
        arr[i] = arr[mixIndex];
        arr[mixIndex] = temp;
    }

    public static void main(String[] args) {
       int testTime = 1000000;
       int maxSize = 100;
       int maxValue = 100;
       boolean succeed =true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generateRandomArray(maxSize,maxValue);
            int[] arr2 = copyArray(arr1);
            selectionSort(arr1);
            comparator(arr2);
            if(!isEqual(arr1,arr2)){
                succeed = false;
                printArray(arr1);
                printArray(arr2);
            }
        }
        System.out.println(succeed ? "good":"bad");
        int[] arr1 = generateRandomArray(maxSize,maxValue);
        printArray(arr1);
        selectionSort(arr1);
        printArray(arr1);
    }

    private static void printArray(int[] arr1) {
        if(arr1 == null){
            return;
        }
        for (int i = 0; i < arr1.length; i++) {
            System.out.print(arr1[i] + " ");
        }
        System.out.println();
    }

    private static boolean isEqual(int[] arr1, int[] arr2) {
       if((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)){
           return false;
       }
       if(arr1 == null && arr2 ==null){
           return true;
       }
       if (arr1.length != arr2.length){
           return false;
       }
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] != arr2[i]) {
                {
                    return false;
                }
            }
        }
        return true;
    }

    private static void comparator(int[] arr2) {
        Arrays.sort(arr2);
    }

    private static int[] copyArray(int[] arr1) {
       if(arr1 == null){
           return arr1;
       }

       int[] res = new int[arr1.length];
        for (int i = 0; i < res.length; i++) {
            res[i] = arr1[i];
        }
        return res;
    }

    private static int[] generateRandomArray(int maxSize, int maxValue) {
       int[] arr = new int[(int)(Math.random() * (maxSize + 1))];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int)((maxValue + 1)* Math.random()) - (int)(maxValue * Math.random());
        }
        return arr;
    }
}
